package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-14
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住信息
     * 
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住信息列表
     * 
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     * 
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住信息
     * 
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住信息
     * 
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息信息
     * 
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     * @param applyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto applyDto) {
        //0、准备工作 列出所有信息项
        CheckInElderDto elderInfo = applyDto.getCheckInElderDto();
        List<ElderFamilyDto> famliyInfo = applyDto.getElderFamilyDtoList();
        CheckInConfigDto checkInInfo = applyDto.getCheckInConfigDto();
        CheckInContractDto contractInfo = applyDto.getCheckInContractDto();

        //1、校验老人是否已经入住，如果入住则提示(抛异常)  - 老人数据存在 且 状态 = 1
        LambdaQueryWrapper<Elder> wrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, elderInfo.getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(wrapper);
        if(ObjectUtil.isNotNull(elder)){
            throw new BaseException("该老人已入住,请勿重复入住");
        }
        //2、如果老人没有入住，更新床位状态为入住中
        Bed bed = bedMapper.selectById(checkInInfo.getBedId());
        bed.setBedStatus(1);
        int result = bedMapper.updateById(bed);
        if(result == 0){
            throw new BaseException("此床位已有人入住，请重新选择床位！");
        }
        //3、新增或更新老人信息
        elder = insertOrupdateElder(elderInfo, bed);
        insertContract(contractInfo, elder, checkInInfo);
        Long checkInId = insertCheckIn(elder, checkInInfo, bed, famliyInfo);
        insertCheckInConfig(checkInInfo, checkInId);
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        //准备结果对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1.设置入住配置响应信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();

        CheckIn checkIn = checkInMapper.selectById(id);
        if(ObjectUtil.isNotEmpty(checkIn)){
            BeanUtils.copyProperties(checkIn, checkInConfigVo);
        }

        CheckInConfig checkInConfig = checkInConfigMapper
                .selectOne(new LambdaQueryWrapper<CheckInConfig>()
                        .eq(CheckInConfig::getCheckInId, id));
        if(ObjectUtil.isNotEmpty(checkInConfig)){
            BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        }

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        //2.设置老人响应信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        //获取老人ID
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        if(ObjectUtil.isNotEmpty(elder)){
            BeanUtils.copyProperties(elder, checkInElderVo);
        }
        //从身份证号获取老人年龄
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //3.设置家属响应信息
        String remark = checkIn.getRemark();
        if(StrUtil.isNotBlank(remark)){
            List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
            checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        }

        //4,设置签约办理响应信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elderId));
        checkInDetailVo.setContract(contract);

        //5.结果返回
        return checkInDetailVo;

    }

    private void insertCheckInConfig(CheckInConfigDto checkInInfo, Long checkInId) {
        //6、新增入住配置信息
        //1.拷贝填充入住配置信息
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInInfo, CheckInConfig.class);
        //2.填充入住ID
        checkInConfig.setCheckInId(checkInId);
        //3.新增
        checkInConfigMapper.insert(checkInConfig);
    }

    private Long insertCheckIn(Elder elder, CheckInConfigDto checkInInfo, Bed bed, List<ElderFamilyDto> famliyInfo) {
        //5、新增入住信息
        CheckIn checkIn = new CheckIn();
        //1、填充老人信息
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //2、填充入住信息
        checkIn.setStartDate(checkInInfo.getStartDate());
        checkIn.setEndDate(checkInInfo.getEndDate());
        checkIn.setNursingLevelName(checkInInfo.getNursingLevelName());
        //3、填充床位信息
        checkIn.setBedNumber(bed.getBedNumber());
        //4、填充家属信息
        if(ObjectUtil.isNotEmpty(famliyInfo)){
           checkIn.setRemark(JSONUtil.toJsonStr(famliyInfo));
        }
        checkInMapper.insert(checkIn);
        return checkIn.getId();
    }

    private void insertContract(CheckInContractDto contractInfo, Elder elder, CheckInConfigDto checkInInfo) {
        //4、新增或更新签约信息
        //4.1拷贝填充合同签约信息
        Contract contract = BeanUtil.toBean(contractInfo, Contract.class);

        //4.2填充老人信息
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //4.3填充合同的开始结束日期、合同编号、状态
        contract.setStartDate(checkInInfo.getStartDate());
        contract.setEndDate(checkInInfo.getEndDate());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setStatus(1);
        //4.4新增
        contractMapper.insert(contract);
    }

    private Elder insertOrupdateElder(CheckInElderDto elderInfo, Bed bed) {
        //1、拷贝填充老人信息
        Elder elder = BeanUtil.toBean(elderInfo, Elder.class);
        //2、填充床位信息
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());

        //3、查询老人是否曾经入住过(有记录且入住状态不等于1)
        LambdaQueryWrapper<Elder>wrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, elderInfo.getIdCardNo())
                .ne(Elder::getStatus, 1);
        Elder elderInDb = elderMapper.selectOne(wrapper);
        //4、如果是，更新
        if(ObjectUtil.isNotNull(elderInDb)){
            elder.setStatus(1);
            elderMapper.updateById(elder);
        }else{
            //5、如果不是，新增
            elderMapper.insert(elder);
        }
        return elder;
    }

}
